package com.smsc.headend.task.engine.executor.impl.deviceconfig;

import cn.hutool.json.JSONUtil;
import com.smsc.headend.common.enums.errorcode.TaskExecuteErrorCode;
import com.smsc.headend.common.utils.RedisUtils;
import com.smsc.headend.module.asset.dmo.ComConfigDMO;
import com.smsc.headend.module.asset.dmo.MeterConfigDMO;
import com.smsc.headend.module.asset.dto.TouDataDTO;
import com.smsc.headend.module.asset.entity.Meter;
import com.smsc.headend.module.common.entity.DeviceOperation;
import com.smsc.headend.module.data.dmo.DeviceSAPandKeys;
import com.smsc.headend.module.data.dto.DataItemDTO;
import com.smsc.headend.module.data.enums.DictionaryType;
import com.smsc.headend.module.data.enums.OperationGroup;
import com.smsc.headend.module.data.enums.OperationName;
import com.smsc.headend.module.protocol.cosem.util.ByteUtils;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.task.engine.dao.TaskDAO;
import com.smsc.headend.task.engine.exception.UDISTaskExecutorException;
import com.smsc.headend.task.engine.executor.TaskExecutor;
import com.smsc.headend.task.engine.facade.DataItemFacade;
import com.smsc.headend.task.engine.handler.impl.deviceconfig.SetActiveCalendarHandler;
import com.smsc.headend.module.task.dto.AtomicTaskState;
import com.smsc.headend.task.engine.service.ConnectorService;
import com.smsc.headend.task.engine.service.FeignAssetManagementService;
import com.smsc.headend.task.engine.service.asset.AssetService;
import com.smsc.headend.task.engine.service.task.TaskPacketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author wxh
 * @date 2020/12/23 15:18
 */
@Slf4j
public class SetTouExecutor implements TaskExecutor {
    @Autowired
    TaskPacketService packetService;
    @Autowired
    ConnectorService connectorService;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    FeignAssetManagementService assetManagementRemoteService;
    @Autowired
    DataItemFacade dataItemFacade;
    @Autowired
    TaskDAO taskDAO;
    @Autowired
    AssetService assetService;

    @Override
    public AtomicTaskState execute(Task task, AtomicTask atomicTask) throws UDISTaskExecutorException {
        log.info("execute step set tou executor");
        DeviceOperation dictionary = assetService.getDictionary(atomicTask.getOperationId(), DictionaryType.Operation.getType());
        Meter meter = getMeter(task, assetService);
        if (task.getMeterId() != null && meter == null) {
            throw new UDISTaskExecutorException(TaskExecuteErrorCode.METER_NOT_EXISTS.toString());
        }
        ComConfigDMO comConfigDMO = assetService.getComConfigById(task.getComId());
//        String interfaceType = comConfigDMO.getInterfaceType();
//        Boolean isShortName = comConfigDMO.getIsShortName();
        MeterConfigDMO meterConfigDMO = null;
        if (task.getMeterId() != null) {
            meterConfigDMO = assetService.getMeterConfigById(task.getMeterId());
        }
        List<DataItemDTO> dataItemDTOList = dataItemFacade.getDataItemsByOperation(meter, null, dictionary, getParameterMap(task, atomicTask), comConfigDMO.getModelId());
        if (CollectionUtils.isEmpty(dataItemDTOList)) {
            throw new UDISTaskExecutorException(TaskExecuteErrorCode.DATAITEM_NOT_EXISTS.toString());
        }
        DeviceSAPandKeys deviceKeys = assetManagementRemoteService.getMeterCommunicationKey(meter.getMeterId(), dataItemDTOList.get(0).getRoleId());

        Map<String, Object> paramMap = this.getParameterMap(task, atomicTask);
        if (!paramMap.containsKey("touDataDTO")) {
            throw new UDISTaskExecutorException(TaskExecuteErrorCode.NO_TOU_SET_DATA_TASK.toString());
        }
        TouDataDTO touDataDTO = JSONUtil.toBean((String)paramMap.get("touDataDTO"), TouDataDTO.class);
        log.info("touDataDTO {}", touDataDTO);

        byte[] packets = getPacketByOperationGroup(atomicTask, meterConfigDMO, dataItemDTOList, meter, deviceKeys, touDataDTO);
        if (packets == null) {
            throw new UDISTaskExecutorException(TaskExecuteErrorCode.PACKETS_IS_NULL.toString());
        }
        log.info(ByteUtils.byteToHexString(packets));
        connectorService.sendPacket(task, atomicTask, dataItemDTOList.get(0).getRoleId(), task.getIsODR(), packets);

        Class handlerClass = getHandlerClass(atomicTask);
        return createAtomicState(handlerClass);
    }

    @Override
    public Boolean handleFailure(Task task, AtomicTask atomicTask, String message) {
        if (atomicTask.getGroupId() == OperationGroup.SetTou.getId().intValue()) {
            String stepOperationName = OperationName.forId(atomicTask.getOperationId()).getName();
            taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), stepOperationName, String.format("step %s failed, [%s]", stepOperationName, message), 3600l, false);
        }
        return true;
    }

    private byte[] getPacketByOperationGroup(AtomicTask atomicTask, MeterConfigDMO meterConfigDMO, List<DataItemDTO> dataItemDTOList, Meter meter, DeviceSAPandKeys deviceSAPandKeys, TouDataDTO touDataDTO) throws UDISTaskExecutorException {
        byte[] packet = null;
        OperationGroup operationGp = OperationGroup.forId(atomicTask.getGroupId().intValue());
        switch (operationGp) {
            case SetTou:
                packet = setTouPacket(atomicTask, meterConfigDMO, meter, dataItemDTOList, deviceSAPandKeys, touDataDTO);
                break;
            default:
                log.info("no implementation of this type {}", operationGp);
        }
        return packet;
    }

    private byte[] setTouPacket(AtomicTask atomicTask, MeterConfigDMO meterConfigDMO, Meter meter, List<DataItemDTO> dataItemDTOList, DeviceSAPandKeys deviceSAPandKeys, TouDataDTO touDataDTO) throws UDISTaskExecutorException {
        byte[] packet = null;
        OperationName opName = OperationName.forId(atomicTask.getOperationId());
        switch (opName) {
            case SetCalendarName:
            case SetDayProfile:
            case SetWeekProfile:
            case SetSeasonProfile:
            case SetActivateCalendarTime:
            case ActionActivateCalendar:
                packet = packetService.setActiveCalendarPacket(dataItemDTOList.get(0), meter, meterConfigDMO, deviceSAPandKeys, touDataDTO);
                break;
            case SetSpecialDays:
                packet = packetService.setSpecialDaysPacket(dataItemDTOList.get(0), meter, meterConfigDMO, deviceSAPandKeys, touDataDTO);
                break;
            case SetFriendlyDays:
                packet = packetService.setFriendlyDaysPacket(dataItemDTOList.get(0), meter, meterConfigDMO, deviceSAPandKeys, touDataDTO);
                break;
        }
        return packet;
    }

    private Class getHandlerClass(AtomicTask atomicTask) throws UDISTaskExecutorException {
        Class cla = null;
        switch (OperationGroup.forId(atomicTask.getGroupId().intValue())) {
            case SetTou:
                cla = SetActiveCalendarHandler.class;
                break;
            default:
                throw new UDISTaskExecutorException(TaskExecuteErrorCode.UNEXPECTED_VALUE.toString() + atomicTask.getGroupId().intValue());
        }
        return cla;
    }

}
